<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>10-职责链模式</title>
</head>
<body>
职责链模式的定义是：使多个对象都有机会处理请求，从而避免请求的发送者和接收者之间的耦合关系<br><br>
将这些对象连成一条链，并沿着这条链传递该请求，直到有一个对象处理它为止<br><br>
</body>
<script type="text/javascript">
	var order500 = function(orderType,pay,stock){
		if(orderType === 1 && pay === true){
			console.log('500元订金预购，得到100优惠券');
		}else{
			return 'nextSuccessor';
		}
	}

	var order200 = function(orderType,pay,stock){
		if(orderType === 2 && pay === true){
			console.log('200元订金预购，得到50优惠券');
		}else{
			return 'nextSuccessor';
		}
	}

	var orderNormal = function(orderType,pay,stock){
		if(stock > 0){
			console.log('普通购买，无优惠券');
		}else{
			console.log('手机库存不足');
		}
	}

	var Chain = function(fn){
		this.fn = fn;
		this.successor = null;
	}
	Chain.prototype.setNextSuccessor = function(successor) {
		return this.successor = successor;
	};
	Chain.prototype.passRequest = function() {
		var ret = this.fn.apply(this,arguments);
		if(ret === 'nextSuccessor'){
			return this.successor && this.successor.passRequest.apply(this.successor,arguments);
		}
		return ret;
	};

	var chainOrder500 = new Chain( order500 );
	var chainOrder200 = new Chain( order200 );
	var orderNormal = new Chain( orderNormal );

	chainOrder500.setNextSuccessor( chainOrder200 );
	chainOrder200.setNextSuccessor( orderNormal );

	chainOrder500.passRequest(1,true,500)
	chainOrder500.passRequest(2,true,500)
	chainOrder500.passRequest(3,true,500)
	chainOrder500.passRequest(1,false,0)


	/* AOP实现职责链 */
	console.log( "### AOP" )
	Function.prototype.after = function(fn) {
		var self = this;
		return function(){
			var ret = self.apply(this,arguments);
			if(ret === 'nextSuccessor'){
				return fn.apply(this,arguments);
			}
			return ret;
		}
	};

	var order = order500.after( order200 ).after( orderNormal );
	order( 1, true, 500 );
	order( 2, true, 500 );
	// order( 1, false, 500 );
</script>
</html>